<?php

require_once dirname(__FILE__) . '/../lib/productosGeneratorConfiguration.class.php';
require_once dirname(__FILE__) . '/../lib/productosGeneratorHelper.class.php';

/**
 * productos actions.
 *
 * @package    tercermilenio
 * @subpackage productos
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12474 2008-10-31 10:41:27Z fabien $
 */
class productosActions extends autoProductosActions {

    public function executeNew(sfWebRequest $request) {
        $this->form = $this->configuration->getForm();
        $this->productos = $this->form->getObject();

        $paramCpr = $request->hasParameter('cpr');
        if ($paramCpr) {
            $this->getUser()->setAttribute('cpr', true);
        } else {
            $this->getUser()->setAttribute('cpr', false);
        }
    }

    protected function addSortCriteria($criteria) {
        if (array(null, null) == ($sort = $this->getSort())) {
            return;
        }

        if ($sort[0] != 'pro_proveedor' && $sort[0] != 'pro_rubro' && $sort[0] != 'pro_marca') {
            $column = ProductosPeer::translateFieldName($sort[0], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_COLNAME);
        }

        if ($sort[0] == 'pro_proveedor') {
            $criteria->addJoin(ProveedoresPeer::PVD_ID, ProductosPeer::PRO_PROVEEDOR);
            $column = ProveedoresPeer::PVD_NOMBRE;
        }
        if ($sort[0] == 'pro_rubro') {
            $criteria->addJoin(RubrosPeer::RUB_ID, ProductosPeer::PRO_RUBRO);
            $column = RubrosPeer::RUB_NOMBRE;
        }
        if ($sort[0] == 'pro_marca') {
            $criteria->addJoin(MarcasPeer::MAR_ID, ProductosPeer::PRO_MARCA);
            $column = MarcasPeer::MAR_NOMBRE;
        }

        if ('asc' == $sort[1]) {
            $criteria->addAscendingOrderByColumn($column);
        } else {
            $criteria->addDescendingOrderByColumn($column);
        }
    }

    protected function processForm(sfWebRequest $request, sfForm $form) {

        $formParameters = $request->getParameter($form->getName());
        if($form->isNew()){
        $formParameters['pro_cantidad'] = $formParameters['pro_a_registrar'];
        $formParameters['pro_disponible'] = $formParameters['pro_a_registrar'];
        }else{
            $object = $this->getRoute()->getObject();
            $cantidad = $object->getProCantidad();
            $disponible = $object->getProDisponible();
            $nuevaCantidad = $cantidad + $formParameters['pro_a_registrar'];
            $nuevoDisponible = $disponible + $formParameters['pro_a_registrar'];
            $formParameters['pro_disponible'] = $nuevaCantidad;
            $formParameters['pro_cantidad'] = $nuevaCantidad;
        }

        $form->bind($formParameters, $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $formValues = $form->getValues();
            $notice = $form->getObject()->isNew() ? 'The item was created successfully.' : 'The item was updated successfully.';

            $form->getObject()->isNew() ? $new = true : $new = false;


            $con = Propel::getConnection();

            try {
                //abrimos la transacción
                $con->beginTransaction();

                //operaciones pertinentes contra la base de datos
                $productos = $form->save();
//var_dump($formValues);exit();
                //if (!empty($productos)) {
                    //if ($new) {
                     //   $productos->setProDisponible($formValues['pro_a_registrar']);
                   /// } else {
                   //     $enStock = $formValues['pro_cantidad'];
                  //      $disponible = $productos->getProDisponible();
                  //      $productos->setProDisponible($disponible + $enStock);
                  //  }
                   // $productos->save();
                //}

                $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $productos)));

                //si todo va bien guardamos los cambios
                $con->commit();
            } catch (Exception $e) {

                // Hacemos rollback de los cambios en caso de fallo
                $con->rollback();
                //devolvemos el error al depurador
                $this->getUser()->setFlash('error', 'The item has not been saved due to some errors.', false);
                $this->redirect(array('sf_route' => 'productos_edit', 'sf_subject' => $productos));
            }

            if ($request->hasParameter('_save_and_add')) {
                $this->getUser()->setFlash('notice', $notice . ' You can add another one below.');

                $this->redirect('@productos_new');
            } else {
                $this->getUser()->setFlash('notice', $notice);
                $cpr = $this->getUser()->getAttribute('cpr');
                $this->getUser()->setAttribute('cpr', null);
                if ($cpr) {
                    $this->redirect('@compras_new');
                } else {
                    //$this->redirect(array('sf_route' => 'productos_edit', 'sf_subject' => $productos));
                    $this->redirect('@productos');
                }
            }
        } else {
            $this->getUser()->setFlash('error', 'The item has not been saved due to some errors.', false);
        }
    }

}
